package com.msh.http.controller;

import com.msh.common.VMSystem;
import com.msh.emq.MqttProducer;
import com.msh.entity.OrderEntity;
import com.msh.service.OrderService;
import com.msh.service.WXPayService;
import com.msh.utils.ConvertUtils;
import com.msh.viewmodel.CreateOrder;
import com.msh.viewmodel.RequestPay;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author :zhangchuanfu
 * @Date :2023/1/14
 * @Time :18:05
 * @description :微信支付接口
 */
@RestController
@RequestMapping("/wxpay")
@Slf4j
public class WxpayController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private WXPayService wxPayService;

    @PostMapping("/requestpay")
    public String requestPay(@RequestBody RequestPay requestPay) throws IOException {
        CreateOrder createOrder = new CreateOrder();
        BeanUtils.copyProperties(requestPay,createOrder);
        createOrder.setPayType("2");//微信支付方式
        OrderEntity orderEntity = orderService.createOrder(createOrder);//创建订单

        orderEntity.setStatus(VMSystem.ORDER_STATUS_PAYED);
        orderEntity.setPayStatus(VMSystem.PAY_STATUS_PAYED);
        orderService.updateById(orderEntity);
        //支付完成通知出货
        orderService.payComplete(orderEntity);
        return "{order:{status: 2}}";
        //return wxPayService.requestPay(orderEntity);//调用发起支付请求
    }

    @RequestMapping("/payNotify")
    @ResponseBody
    public void payNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            //输入流转换为xml字符串
            String xml = ConvertUtils.convertToString(request.getInputStream());
            wxPayService.notify(xml);

            //给微信支付一个成功的响应
            response.setContentType("text/xml");
            String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            response.getWriter().write(data);
        } catch (Exception e) {
            log.error("支付回调处理失败",e);
        }
    }

}
